import Vue from 'vue'
import nedb from '../../db/nedb'
import base64 from '@/common/base64'


// state
const state = {
    // =========== 功能大全用到的变量 =============
    qrCode: {}, // 微信二维码
    newFriends: [], // 新的好友
    addFriends: [], // 添加好友的列表
    zombies: [], // 僵尸粉结果
    autoTaskConfig: {}, // 自动任务的配置文件
    autoReply: [], // 自动回复的配置文件
    autoAddFriendLog: [], // 自动加好友日志
    phonesList: [], // 号码列表
    autoHiConfig: {
        Content: '',
        ContentType: 'text'
    }, // 自动打造胡的配置文件
    searchResults: [], // 好友全局搜索的结果
    findContactTaskResult: [], // 好友全局搜索的结果
    // =========== 朋友圈用到的变量 ===============
    currentCircles: [], // 朋友圈页面所选微信的朋友圈列表
    friendCircleLog: [], // 朋友圈页面所选微信的日志
    circleFriends: [], // 朋友圈页面所选微信的通讯录
    circleLabels: [], // 朋友圈页面所选微信的标签
    // =========== 群发用到的变量 =================
    groupSendLog: [], // 群发助手页面所选微信的群发日志
    groupSendFriends: [], // 群发助手页面所选微信的通讯录
    groupSendRooms: [], // 群发助手页面所选微信的群聊列表
    groupSendLabels: [], // 群发助手页面所选微信的标签列表
    // =========== 会话页面用到的变量 =============
    conversations: [], // 会话页面所选微信的会话列表
    friends: [], // 会话页面所选微信的通讯录
    friendsAll: [], // 会话页面所选微信的通讯录
    labels: [], // 会话页面所选微信的标签列表
    chatRooms: [], // 会话页面所选微信的群聊列表
    chatRoomsAll: [], // 会话页面所选微信的群聊列表不分页
    newMessageNotice: {}, // 会话页面所有微信的最新未读消息数量
    members: [], // 会话页面用到的陌生人列表
    conversationQrCode: {}, // 会话页面用到的微信的二维码
    chatRoomQrCode: {}, // 会话页面用到的群聊的二维码
    conversationCircles: [], // 会话页面用到的朋友圈

    friendsMap: {}, // 会话页面所选微信的好友信息
    chatRoomsMap: {}, // 会话页面所选微信的群聊信息
    luckMoneyMap: {}, // 红包账单

    myReply: [], // 快捷语页面我的术语
    currentChats: [], // 会话页面的会话列表
}

// getters
const getters = {
    indexedDB: state => state.indexedDB,
    // ===================== 功能大全用到的变量===================
    qrCode: state => state.qrCode,
    findContactTaskResult: state => state.findContactTaskResult,
    newFriends: state => state.newFriends,
    addFriends: state => state.addFriends,
    zombies: state => state.zombies,
    autoTaskConfig: state => state.autoTaskConfig,
    autoReply: state => state.autoReply,
    autoAddFriendLog: state => state.autoAddFriendLog,
    phonesList: state => state.phonesList,
    autoHiConfig: state => state.autoHiConfig,
    searchResults: state => state.searchResults,
    // ===================== 朋友圈用到的变量=====================
    currentCircles: state => state.currentCircles,
    circleFriends: state => state.circleFriends,
    circleLabels: state => state.circleLabels,
    friendCircleLog: state => state.friendCircleLog,
    // ===================== 群发用到的变量  =====================
    groupSendLog: state => state.groupSendLog,
    groupSendFriends: state => state.groupSendFriends,
    groupSendRooms: state => state.groupSendRooms,
    groupSendLabels: state => state.groupSendLabels,
    // ===================== 会话页面用到的变量===================
    conversations: state => state.conversations,
    friends: state => state.friends,
    friendsAll: state => state.friendsAll,
    chatRooms: state => state.chatRooms,
    chatRoomsAll: state => state.chatRoomsAll,
    newMessageNotice: state => state.newMessageNotice,
    friendsMap: state => state.friendsMap,
    chatRoomsMap: state => state.chatRoomsMap,
    luckMoneyMap: state => state.luckMoneyMap,
    myReply: state => state.myReply,
    currentChats: state => state.currentChats,
    labels: state => state.labels,
    members: state => state.members,
    conversationQrCode: state => state.conversationQrCode,
    chatRoomQrCode: state => state.chatRoomQrCode,
    conversationCircles: state => state.conversationCircles,
}

// actions
const actions = {
    // ===================== 功能大全用到的变量===================
    // 从nedb获取newFriends数据
    SetNewFriends({ commit }, wechatId) {
        nedb.newFriends.findOne({ WeChatId: wechatId }, (err, doc) => {
            if (err) return
            commit('SET_NEW_FRIENDS', doc ? doc : [])
        })
    },
    // 更新或添加nedb中的newFriends数据
    UpdateOrAddNewFriends({ dispatch }, message) {
        // 如果没有数据 返回
        if (message.Requests.length === 0) return
        // 查数据库有没有记录
        nedb.newFriends.findOne({ WeChatId: message.WeChatId }, (err, doc) => {
            if (err) return
            if (doc) {
                let oldRequests = doc.Requests
                let newRequests = message.Requests
                let newRequestsMap = []
                for (const nreq of newRequests) {
                    newRequestsMap.push(nreq.FriendId)
                }
                for (const oreq of oldRequests) {
                    if (newRequestsMap.indexOf(oreq.FriendId) === -1) {
                        newRequests.push(oreq)
                    }
                }
                nedb.newFriends.update({ WeChatId: message.WeChatId }, { $set: { Requests: newRequests } }, {}, (err, numReplaced) => {
                    if (err) return
                    dispatch('SetNewFriends', message.WeChatId)
                })
            } else {
                nedb.newFriends.insert(message, (err, newDoc) => {
                    if (err) return
                    dispatch('SetNewFriends', message.WeChatId)
                })
            }
        })
    },
    // 单个好友请求 添加到newFriends
    UpdateNewFriendsByOne({ rootGetters, dispatch }, message) {
        // 查数据库有没有记录
        nedb.newFriends.findOne({ WeChatId: message.WeChatId }, (err, doc) => {
            if (err) return
            if (doc) {
                let oldRequests = doc.Requests
                let oldRequestsMap = []
                for (const oreq of oldRequests) {
                    oldRequestsMap.push(oreq.FriendId)
                }
                if (oldRequestsMap.indexOf(message.FriendId) === -1) {
                    oldRequests.push(message)
                } else {
                    let oid = oldRequestsMap.indexOf(message.FriendId)
                    oldRequests.splice(oid, 1, message)
                }
                nedb.newFriends.update({ WeChatId: message.WeChatId }, { $set: { Requests: oldRequests } }, {}, (err, numReplaced) => {
                    if (err) return
                    if (message.WeChatId === rootGetters['currentWechats']['addFriend']) {
                        dispatch('SetNewFriends', message.WeChatId)
                    }
                })
            } else {
                let friends = {
                    userId: rootGetters.userId,
                    ModifyTime: message.ReqTime,
                    Requests: [message],
                    WeChatId: message.WeChatId
                }
                nedb.newFriends.insert(friends, (err, newDoc) => {
                    if (err) return
                    if (message.WeChatId === rootGetters['currentWechats']['addFriend']) {
                        dispatch('SetNewFriends', message.WeChatId)
                    }
                })
            }
        })
    },
    // 从nedb获取addFreinds数据
    SetAddFriends({ rootGetters, commit }, wechatId) {
        nedb.addFriendTask
            .find({ userId: rootGetters.userId, WeChatId: wechatId }) // 全部
            .sort({ TaskId: -1 }) // 降序
            // .limit(20) // 20条
            .exec((err, docs) => {
                if (!err && docs) {
                    commit('SET_ADD_FRIENDS', docs)
                }
            })
    },
    // 更新或添加nedb中的addFreinds数据
    AddOrUpdateAddFriends({ dispatch }, message) {
        // 查数据库有没有记录
        nedb.addFriendTask.findOne({ TaskId: message.TaskId }, (err, doc) => {
            if (err) return
            if (doc) {
                nedb.addFriendTask.update({ TaskId: message.TaskId }, { $set: { result: message.result } }, {}, (err, numReplaced) => {
                    if (err) return
                    dispatch('SetAddFriends', message.WeChatId)
                })
            } else {
                nedb.addFriendTask.insert(message, (err, newDoc) => {
                    if (err) return
                    dispatch('SetAddFriends', message.WeChatId)
                })
            }
        })
    },
    // 添加nedb中的findContactTask数据
    AddFindContactTask({ dispatch }, doc) {
        nedb.findContactTask.insert(doc, (err, newDoc) => {
            if (err) return
            dispatch('SetFindContactTask')
        })
    },
    // 更新nedb中的findContactTask数据
    UpdateFindContactTask({ dispatch }, message) {
        // 查数据库有没有记录
        nedb.findContactTask
            .find({ Content: message.SearchText })
            .sort({ time: -1 })
            .limit(1)
            .exec((err, docs) => {
                nedb.findContactTask.update(
                    { _id: docs[0]._id },
                    {
                        $set: message
                    },
                    { upsert: false },
                    (err, newDoc) => {
                        if (err) return
                        dispatch('SetFindContactTask')
                    })
            })
    },
    // 查询FindContactTask
    SetFindContactTask({ commit }) {
        nedb.findContactTask
            .find({})
            .sort({ time: -1 }) // 降序
            // .limit(20) // 20条
            .exec((err, docs) => {
                if (!err && docs) {
                    commit('SET_FIND_CONTACT_TASK', docs)
                }
            })
    },
    // 从nedb获取zombies数据
    SetZombies({ rootGetters, commit }, wechatId) {
        nedb.zombies
            .find({ userId: rootGetters.userId, WeChatId: wechatId }) // 全部
            .sort({ TaskId: -1 }) // 降序
            // .limit(20) // 20条
            .exec((err, docs) => {
                if (!err && docs) {
                    commit('SET_ZOMBIES', docs)
                }
            })
    },
    // 更新或添加nedb中的zombies数据
    AddOrUpdateZombies({ rootGetters, dispatch }, message) {
        message.userId = rootGetters.userId
        nedb.zombies.insert(message, (err, newDoc) => {
            if (err) return
            dispatch('SetZombies', message.WeChatId)
        })
    },
    // 从nedb获取qrCode数据
    SetQrCode({ commit }, wechatId) {
        nedb.qrcode.findOne({ WeChatId: wechatId, ChatRoomId: -1 }, (err, doc) => {
            if (err) return
            commit('SET_QR_CODE', doc ? doc : { WeChatId: '', ChatRoomId: -1, QrCodeUrl: '', ModifyTime: 0 })
        })
    },
    // 更新或添加nedb中的qrCode数据
    UpdateQrCode({ rootGetters, dispatch }, qrcode) {
        qrcode.ModifyTime = new Date().getTime()
        nedb.qrcode.update(
            {
                WeChatId: qrcode.WeChatId,
                ChatRoomId: qrcode.ChatRoomId
            },
            {
                $set: {
                    WeChatId: qrcode.WeChatId,
                    QrCodeUrl: qrcode.QrCodeUrl,
                    ChatRoomId: qrcode.ChatRoomId,
                    ModifyTime: qrcode.ModifyTime
                }
            },
            { upsert: true },
            (err, numReplaced) => {
                if (err) return
                let currentWeChatId = rootGetters['conversation/currentWeChatId']
                let currentFriend = rootGetters['conversation/currentFriends'][currentWeChatId]
                // 更新群聊的二维码
                if (currentFriend && currentFriend.UserName === qrcode.ChatRoomId) {
                    dispatch('SetChatRoomQrCode', currentFriend)
                }
                if (qrcode.ChatRoomId === -1) {
                    // 更新工具页面的qrcode
                    let toolsWechatId = rootGetters['currentWechats']['qrCode']
                    if (qrcode.WeChatId === toolsWechatId) {
                        dispatch('SetQrCode', toolsWechatId)
                    }
                    // 更新会话页面的二维码
                    if (currentWeChatId === qrcode.WeChatId) {
                        dispatch('SetConversationQrCode', currentWeChatId)
                    }
                }
            }
        )
    },
    // 从nedb获取autoReply数据
    SetAutoReply({ rootGetters, commit }) {
        nedb.autoReply
            .find({ userId: rootGetters.userId })
            .sort({ modifyTime: -1 })
            .exec((err, docs) => {
                if (err) return
                if (docs) {
                    commit('SET_AUTP_REPLY', docs)
                }
            })
    },
    // 更新或添加nedb中的autoReply数据
    UpdateOrAddAutoReply({ rootGetters, dispatch }, autoReplyForm) {
        autoReplyForm.userId = rootGetters.userId
        autoReplyForm.modifyTime = new Date().getTime()
        nedb.autoReply.update(
            { userId: rootGetters.userId, keyWord: autoReplyForm.keyWord },
            autoReplyForm,
            { upsert: true },
            (err, numReplaced) => {
                if (err) return
                dispatch('SetAutoReply')
            })
    },
    // 删除nedb中的autoReply数据
    DeleteAutoReply({ rootGetters, dispatch }, row) {
        nedb.autoReply.remove(
            { _id: row._id },
            { multi: false },
            (err, numRemoved) => {
                if (err) return
                dispatch('SetAutoReply')
            }
        )
    },
    // 从nedb获取autoHiConfig数据
    SetAutoHiConfig({ rootGetters, commit }) {
        nedb.autoHiConfig.findOne({ userId: rootGetters.userId }, (err, doc) => {
            if (err) return
            if (doc) {
                commit('SET_AUTP_HI_CONFIG', doc)
            }
        })
    },
    // 更新或添加nedb中的autoHiConfig数据
    UpdateOrAddAutoHiConfig({ rootGetters, dispatch }, autoHi) {
        autoHi.userId = rootGetters.userId
        nedb.autoHiConfig.update(
            { userId: rootGetters.userId },
            autoHi,
            { upsert: true },
            (err, doc) => {
                if (err) return
                dispatch('SetAutoHiConfig')
            }
        )
    },
    // 自动打招呼
    AutoHi({ getters, dispatch }, message) {
        if (
            (message.ContentType === 'System' &&
                message.Content.indexOf('5Y+v5Lul5byA5aeL6IGK5aSp5LqG') >= 0) ||
            message.Content.indexOf(
                '5oiR6YCa6L+H5LqG5L2g55qE5pyL5Y+L6aqM6K+B6K+35rGC77yM546w5Zyo5oiR5Lus5Y+v5Lul5byA5aeL6IGK5aSp5LqG'
            ) >= 0
        ) {
            let autoHiConfig = getters.autoHiConfig
            if (autoHiConfig.Content) {
                let hiMsg = {
                    WeChatId: message.WeChatId,
                    FriendId: message.FriendId,
                    ContentType: 'Text',
                    Content: autoHiConfig.Content,
                }
                dispatch('websocket/TalkToFriendTask', hiMsg, { root: true })
            }
        }
    },
    // 自动回复
    AutoReply({ getters, dispatch }, message) {
        let autoReply = getters.autoReply
        if (message.ContentType === 'Text' && autoReply.length > 0) {
            let replyMap = {}
            for (const ar of autoReply) {
                replyMap[ar.keyWord] = ar
            }
            let word = base64.decode(message.Content)
            // 如果匹配关键词
            if (replyMap[word]) {
                let replyMsg = {
                    WeChatId: message.WeChatId,
                    FriendId: message.FriendId,
                    ContentType: replyMap[word].msgType,
                    Content: replyMap[word].replyMsg,
                }
                dispatch('websocket/TalkToFriendTask', replyMsg, { root: true })
            }
        }
    },
    // 全局搜索
    FindFriendsByConditions({ rootGetters, commit }, conditions) {
        let ff = {
            userId: rootGetters.userId
        }
        if (conditions.Memo) {
            ff.Memo = { $regex: new RegExp(".*" + conditions.Memo + ".*") }
        }
        if (conditions.FriendNo) {
            ff.FriendNo = { $regex: new RegExp(".*" + conditions.FriendNo + ".*") }
        }
        if (conditions.FriendNick) {
            ff.FriendNick = { $regex: new RegExp(".*" + conditions.FriendNick + ".*") }
        }
        nedb.friends.find(ff, (err, docs) => {
            if (err) return
            commit('SET_SEARCH_CONDITIONS', docs || [])
        })
    },
    // ===================== 朋友圈用到的变量 =====================
    // 从nedb获取我的朋友圈数据 ok
    SetCurrentCircles({ commit }, wechatId) {
        nedb.circles.findOne({ WeChatId: wechatId, FriendId: wechatId }, (err, doc) => {
            if (err) return
            commit('SET_CURRENT_CIRCLES', doc && doc.Circles ? doc.Circles : [])
        })
    },
    // 更新或添加nedb中的circles数据 ok
    UpdateOrAddCircles({ rootGetters, dispatch }, message) {
        let circles = message.Circles
        let wechatId = message.WeChatId
        let friendId = circles[0].WeChatId

        // 我的朋友圈
        let circleMyWeChatId = rootGetters['currentWechats']['circleMy']
        // 好友的朋友圈
        let currentFriends = rootGetters['conversation/currentFriends']
        let currentWeChatId = rootGetters['conversation/currentWeChatId']
        let currentFriend = currentFriends[currentWeChatId]

        nedb.circles.findOne({ WeChatId: wechatId, FriendId: friendId }, (err, doc) => {
            if (err) return
            if (doc) {
                // 老的数据
                let oldCircles = doc.Circles
                // 合并后的数据
                let totalCirlces = circles.concat(oldCircles);
                // 去重
                let temp = {};   //用于name判断重复
                let result = [];  //最后的新数组
                totalCirlces.map(function (item, index) {
                    if (!temp[item.CircleId]) {
                        result.push(item);
                        temp[item.CircleId] = true;
                    }
                });
                nedb.circles.update(
                    { WeChatId: wechatId, FriendId: friendId },
                    { $set: { Circles: result } },
                    {},
                    (err, numReplaced) => {
                        if (err) return
                        if (wechatId === friendId && wechatId === circleMyWeChatId) {
                            dispatch('SetCurrentCircles', wechatId)
                        }
                        if (wechatId !== friendId && JSON.stringify(currentFriend) !== '{}' && wechatId === currentFriend.WeChatId && friendId === currentFriend.FriendId) {
                            dispatch('SetConversationCircles', currentFriend)
                        }
                    })
            } else {
                nedb.circles.insert({ WeChatId: wechatId, FriendId: friendId, Circles: circles }, (err, newDoc) => {
                    if (err) return
                    if (wechatId === friendId && wechatId === circleMyWeChatId) {
                        dispatch('SetCurrentCircles', wechatId)
                    }
                    if (wechatId !== friendId && JSON.stringify(currentFriend) !== '{}' && wechatId === currentFriend.WeChatId && friendId === currentFriend.FriendId) {
                        dispatch('SetConversationCircles', currentFriend)
                    }
                })
            }
        })
    },
    // 更新朋友圈的图片数据
    UpdateCirclesImgs({ rootGetters, dispatch }, message) {
        let circle = message.Circle
        let wechatId = message.WeChatId
        dispatch('UpdateOrAddCircles', { WeChatId: wechatId, Circles: [circle] })
    },
    // 删除nedb中的circles数据 ok
    RemoveCircles({ rootGetters, dispatch }, message) {
        let wechatId = message.WeChatId
        let circleMyWeChatId = rootGetters['currentWechats']['circleMy']
        nedb.circles.findOne({ WeChatId: wechatId, FriendId: wechatId }, (err, doc) => {
            if (err) return
            if (doc && doc.Circles) {
                let circles = doc.Circles
                let i = 0
                let flag = false
                for (const circle of circles) {
                    if (circle.CircleId === message.CircleId) {
                        flag = true
                        break
                    }
                    i++
                }
                if (!flag) return
                circles.splice(i, 1)
                nedb.circles.update(
                    { WeChatId: wechatId, FriendId: wechatId },
                    { $set: { Circles: circles } },
                    {},
                    (err, numReplaced) => {
                        if (err) return
                        if (wechatId === circleMyWeChatId) {
                            dispatch('SetCurrentCircles', wechatId)
                        }
                    })
            }
        })
    },
    // 将朋友圈操作保存到nedb
    AddCircleTask({ rootGetters, dispatch }, doc) {
        doc.userId = rootGetters.userId
        doc.result = 0 // 0表示初始状态 1表示成功 2表示失败
        let circleLogWechatId = rootGetters['currentWechats']['circleLog']
        nedb.circleTask.insert(doc, (err, newDoc) => {
            if (err) return
            // 更新日志
            if (doc.WeChatId === circleLogWechatId) {
                dispatch('SetFriendCircleLog', circleLogWechatId)
            }
        })
    },
    // 更新朋友圈任务结果
    UpdateCircleTask({ rootGetters, dispatch }, mj) {
        let flag = mj.Success ? 1 : 2
        let circleLogWechatId = rootGetters['currentWechats']['circleLog']
        nedb.circleTask.update(
            { TaskId: mj.TaskId },
            { $set: { result: flag } },
            {},
            (err, count) => {
                if (err) return
                // 更新日志
                if (mj.WeChatId === circleLogWechatId) {
                    dispatch('SetFriendCircleLog', circleLogWechatId)
                }
            }
        )
    },
    // 查询朋友圈的日志
    SetFriendCircleLog({ commit, rootGetters }, wechatId) {
        nedb.circleTask.find({ userId: rootGetters.userId, WeChatId: wechatId }, (err, docs) => {
            if (err) return
            commit('SET_FRIEND_CIRCLE_LOG', docs)
        })
    },
    // 朋友圈页面当前所选微信的好友列表
    SetCircleFriends({ commit }, wechatId) {
        nedb.friends.find({ WeChatId: wechatId }, (err, docs) => {
            if (err) return
            commit('SET_CIRCLE_FRIENDS', docs || [])
        })
    },
    // 从nedb获取标签数据
    SetCircleLabels({ commit }, wechatId) {
        nedb.labels.findOne({ WeChatId: wechatId }, (err, doc) => {
            if (err) return
            if (doc) {
                commit('SET_CIRCLE_LABELS', doc)
            }
        })
    },
    // ===================== 群发用到的变量 =======================
    // 设置群发助手页面 当前微信的好友列表
    SetGroupSendFriends({ commit }, wechatId) {
        nedb.friends.find({ WeChatId: wechatId }, (err, docs) => {
            if (err) return
            commit('SET_GROUP_SEND_FRIENDS', docs || [])
        })
    },
    // 设置群发助手页面 当前微信的群聊列表
    SetGroupSendRooms({ commit }, wechatId) {
        nedb.chatRooms.find({ WeChatId: wechatId }, (err, docs) => {
            if (err) return
            commit('SET_GROUP_SEND_ROOMS', docs || [])
        })
    },
    // 将群发的任务保存到数据库
    AddGroupSendTask2Nedb({ rootGetters, dispatch }, doc) {
        doc.userId = rootGetters.userId
        doc.result = 0
        let groupLogWeChatId = rootGetters['currentWechats']['groupLog']
        nedb.groupSendTask.insert(doc, (err, newDoc) => {
            if (err) return
            if (doc.WeChatId === groupLogWeChatId) {
                dispatch('SetGroupSendLog', doc.WeChatId)
            }
        })
    },
    // 更新群发日志
    UpdateGroupSendTask({ rootGetters, dispatch, commit }, mj) {
        let taskId = mj.TaskId
        let flag = mj.Success ? 1 : 2
        let wechatId = mj.WeChatId
        let groupLogWeChatId = rootGetters['currentWechats']['groupLog']
        nedb.groupSendTask.update(
            { TaskId: taskId },
            { $set: { result: flag } },
            {},
            (err, numReplaced) => {
                if (err) return
                if (wechatId === groupLogWeChatId) {
                    dispatch('SetGroupSendLog', wechatId)
                }
            }
        )
    },
    // 查询群发的日志
    SetGroupSendLog({ commit, rootGetters }, wechatId) {
        nedb.groupSendTask.find({ userId: rootGetters.userId, WeChatId: wechatId }, (err, docs) => {
            if (err) return
            commit('SET_GROUP_SEND_LOG', docs)
        })
    },
    // 从nedb获取标签数据
    SetGroupSendLabels({ commit }, wechatId) {
        nedb.labels.findOne({ WeChatId: wechatId }, (err, doc) => {
            if (err) return
            if (doc) {
                commit('SET_GROUP_SEND_LABELS', doc)
            }
        })
    },
    // ===================== 会话页面用到的变量 ===================
    // ===================== 会话页面用到的变量 ===================
    // ===================== 会话页面用到的变量 ===================
    // 添加新的标签
    AddLabel({ dispatch }, message) {
        let label = message.Label
        let wechatId = message.WeChatId
        let newLable = {
            LabelId: label.LabelId,
            LabelName: label.LabelName
        }
        nedb.labels.findOne({ WeChatId: wechatId }, (err, doc) => {
            if (err) return
            let newDoc = {
                Labels: [newLable],
                WeChatId: wechatId
            }
            if (doc) {
                let labels = doc.Labels
                let flag = true
                for (const label of labels) {
                    if (label.LabelId === newLable.LabelId) {
                        label.LabelName = newLable.LabelName
                        flag = false
                        break
                    }
                }
                if (flag) {
                    labels.push(newLable)
                }
                newDoc.Labels = labels
            }
            dispatch('UpdateOrAddLabels', newDoc)
        })
    },
    // 删除标签
    DeleteLabel({ dispatch }, message) {
        let wechatId = message.WeChatId
        nedb.labels.findOne({ WeChatId: wechatId }, (err, doc) => {
            if (err) return
            if (doc) {
                let newLables = []
                for (const label of doc.Labels) {
                    if (label.LabelId !== message.LabelId) {
                        newLables.push(label)
                    }
                }
                let newDoc = {
                    Labels: newLables,
                    WeChatId: wechatId
                }
                dispatch('UpdateOrAddLabels', newDoc)
            }
        })
    },
    // 从nedb获取标签数据
    SetLabels({ commit }, wechatId) {
        nedb.labels.findOne({ WeChatId: wechatId }, (err, doc) => {
            if (err) return
            if (doc) {
                commit('SET_LABELS', doc)
            }
        })
    },
    // 更新或插入nedb的labels
    UpdateOrAddLabels({ rootGetters, dispatch }, message) {
        let wechatId = message.WeChatId
        nedb.labels.update(
            { WeChatId: message.WeChatId },
            message,
            { upsert: true },
            (err, numReplaced) => {
                if (err) return
                dispatch('SetLabels', wechatId)
            }
        )
    },
    // 从nedb获取会话数据
    SetConversations({ commit }, wechatId) {
        nedb.conversations
            .findOne({
                WeChatId: wechatId
            }, (err, doc) => {
                if (err) return
                commit('SET_CONVERSATIONS', doc && doc.Convers ? doc.Convers : [])
            })
    },
    // 更新或添加nedb中的conversations数据
    UpdateOrAddConversations({ rootGetters, dispatch }, message) {
        let conversations = message.Convers
        let wechatId = message.WeChatId
        let currentWeChatId = rootGetters['conversation/currentWeChatId']

        nedb.conversations.findOne({ WeChatId: wechatId }, (err, doc) => {
            if (err) return
            if (doc) {
                let oldConversations = doc.Convers
                let newConversMap = []
                for (const conversation of conversations) {
                    newConversMap.push(conversation.UserName)
                }
                for (const oc of oldConversations) {
                    if (newConversMap.indexOf(oc.UserName) === -1) {
                        conversations.push(oc)
                    }
                }
                nedb.conversations.update(
                    { WeChatId: wechatId },
                    { $set: { Convers: conversations } },
                    {},
                    (err, numReplaced) => {
                        if (err) return
                        // 更新conversations
                        if (wechatId === currentWeChatId) {
                            dispatch('SetConversations', wechatId)
                        }
                        // 更新newMessageNotice
                        dispatch('UpdateNewMessageNotice', wechatId)
                    })
            } else {
                nedb.conversations.insert({ WeChatId: wechatId, Convers: conversations }, (err, newDoc) => {
                    if (err) return
                    if (wechatId === currentWeChatId) {
                        // 更新conversations
                        dispatch('SetConversations', wechatId)
                    }
                    // 更新newMessageNotice
                    dispatch('UpdateNewMessageNotice', wechatId)
                })
            }
        })
    },
    // FriendTalkNotice添加到conversations
    UpdateOrAddConversationsByTalk({ rootGetters, dispatch }, talk) {
        let wechatId = talk.WeChatId
        let digest = ''
        let conver = {
            UserName: talk.FriendId, // 好友微信内部全局唯一识别码
            Digest: '', // 消息概要显示
            // DigestUser: 3, // 消息发送者id
            // IsSend: false, // 最后消息是否自己发送
            MsgCnt: 1, // 消息条数
            UnreadCnt: 1, // 未读消息条数
            UpdateTime: talk.CreateTime, // 最后消息的时间
        }
        let currentFriendId = rootGetters['conversation/currentFriendId']
        // 是自己发送的
        if (talk.IsSend) {
            conver.IsSend = true
        }
        // 群消息 发送者
        if (talk.FriendId.indexOf('@chatroom') > 0) {
            conver.DigestUser = base64.decode(talk.Content).split(':')[0]
        }
        // decode 内容
        switch (talk.ContentType) {
            case 'Text':
                digest = base64.decode(talk.Content)
                if (talk.FriendId.indexOf('@chatroom') > 0) {
                    digest = unescape(
                        escape(digest.replace(/.*?:/, '')).replace('%0A', '%20')
                    ).replace(' ', '')
                }
                break
            case 'Picture':
            case 2:
                digest = '[图片]'
                break
            // 语音 3
            case 'Voice':
            case 3:
                digest = '[语音]'
                break
            // 视频 4
            case 'Video':
            case 4:
                digest = '[视频]'
                break
            // 系统消息 5
            case 'System':
            case 5:
                digest = '[系统消息]'
                break
            // 链接消息 6
            case 'Link':
            case 6:
                digest = '[链接]'
                break
            // 扩展的链接消息（小程序分享等），内容为xml格式，暂未使用 7
            case 'LinkExt':
            case 7:
                digest = '[扩展的链接消息]'
                break
            // 文件 8
            case 'File':
            case 8:
                digest = '[文件]'
                break
            // 名片 9
            case 'NameCard':
            case 9:
                digest = '[名片]'
                break
            // 位置信息 10
            case 'Location':
            case 10:
                digest = '[位置消息]'
                break
            // 红包 11
            case 'LuckyMoney':
            case 11:
                digest = '[链接]'
                break
            // 转账 12
            case 'MoneyTrans':
            case 12:
                digest = '[红包]'
                break
            // 小程序 13
            case 'WeApp':
            case 13:
                digest = '[小程序]'
                break
            // Emoji 14
            case 'Emoji':
            case 14:
                digest = '[Emoji]'
                break
            // 群管理消息 15
            case 'RoomManage':
            case 15:
                digest = '[群管理消息]'
                break
            // 红包系统消息 16
            case 'Sys_LuckyMoney':
            case 16:
                digest = '[红包系统消息]'
                break
            // 群系统消息 17
            case 'RoomSystem':
            case 17:
                digest = '[群系统消息]'
                break
            // 不支持的消息
            default:
                digest = '[不支持的消息]'
                break
        }
        conver.Digest = digest
        // 设置消息总数和未读消息
        nedb.conversations.findOne({ WeChatId: wechatId }, (err, doc) => {
            if (err) return
            if (doc) {
                let oldConversations = doc.Convers || []
                let flag = false
                let oldConver = {}
                for (const oc of oldConversations) {
                    if (oc.UserName === talk.FriendId) {
                        oldConver = oc
                        flag = true
                        break
                    }
                }
                if (flag) {
                    conver.MsgCnt = oldConver.MsgCnt ? oldConver.MsgCnt + 1 : 1
                    conver.UnreadCnt = oldConver.UnreadCnt ? oldConver.UnreadCnt + 1 : 1
                }
                // 如果是在看的消息
                if (talk.FriendId === currentFriendId) {
                    conver.UnreadCnt = 0
                }
                let convers = {
                    WeChatId: wechatId,
                    Convers: [
                        conver
                    ]
                }
                dispatch('UpdateOrAddConversations', convers)
            } else {
                let convers = {
                    WeChatId: wechatId,
                    Convers: [
                        conver
                    ]
                }
                dispatch('UpdateOrAddConversations', convers)
            }
        })
    },
    // 删除nedb中的指定微信的conversations
    RemoveAllConversationsByWechatId({ dispatch }, wechatId) {
        nedb.conversations.remove({ WeChatId: wechatId }, { multi: true }, (err, removedDocs) => {
            if (err) return
            dispatch('SetConversations', wechatId)
        })
    },
    // 删除nedb中指定微信的指定好友的conversations
    RemovConversationsByFriendId({ rootGetters, dispatch }, message) {
        let wechatId = message.WeChatId
        let currentWeChatId = rootGetters['conversation/currentWeChatId']
        nedb.conversations.findOne({ WeChatId: wechatId }, (err, doc) => {
            if (err) return
            if (doc) {
                let newConvers = []
                for (const conver of doc.Convers) {
                    if (conver.UserName !== message.RoomId) {
                        newConvers.push(conver)
                    }
                }
                nedb.conversations.update(
                    { WeChatId: wechatId },
                    { $set: { Convers: newConvers } },
                    {},
                    (err, numReplaced) => {
                        if (err) return
                        // 更新conversations
                        if (wechatId === currentWeChatId) {
                            dispatch('SetConversations', wechatId)
                        }
                        // 更新newMessageNotice
                        dispatch('UpdateNewMessageNotice', wechatId)
                    })
            }
        })
    },
    // 设置Conversations为已读
    SetUnreadCnt({ rootGetters, dispatch }, message) {
        let wechatId = message.WeChatId
        let currentWeChatId = rootGetters['conversation/currentWeChatId']

        nedb.conversations.findOne({ WeChatId: wechatId }, (err, doc) => {
            if (err) return
            if (doc) {
                let conversations = doc.Convers
                for (const conversation of conversations) {
                    if (conversation.UserName === message.FriendId) {
                        conversation.UnreadCnt = 0
                        break
                    }
                }
                nedb.conversations.update(
                    { WeChatId: wechatId },
                    { $set: { Convers: conversations } },
                    {},
                    (err, numReplaced) => {
                        if (err) return
                        // 更新conversations
                        if (wechatId === currentWeChatId) {
                            dispatch('SetConversations', wechatId)
                        }
                        // 更新newMessageNotice
                        dispatch('UpdateNewMessageNotice', wechatId)
                    })
            }
        })
    },
    // 统计每个微信的未读消息
    SetNewMessageNotice: ({ commit }, wechatId) => {
        nedb.conversations
            .find({}, (err, docs) => {
                if (err) return {}
                let msgMap = {}
                for (const doc of docs) {
                    let unreadCnt = 0
                    for (const conver of doc.Convers) {
                        if (conver.UnreadCnt) {
                            unreadCnt = unreadCnt + conver.UnreadCnt
                        }
                    }
                    msgMap[doc.WeChatId] = unreadCnt
                }
                commit('SET_NEW_MESSAGE_NOTICE', msgMap)
            })
    },
    // 更新指定微信的未读消息
    UpdateNewMessageNotice: ({ commit }, wechatId) => {
        nedb.conversations
            .findOne({ WeChatId: wechatId }, (err, doc) => {
                if (err || !doc) return
                let msgMap = {}
                let unreadCnt = 0
                for (const conver of doc.Convers) {
                    if (conver.UnreadCnt) {
                        unreadCnt = unreadCnt + conver.UnreadCnt
                    }
                }
                msgMap[doc.WeChatId] = unreadCnt
                commit('SET_NEW_MESSAGE_NOTICE', msgMap)
            })
    },
    // 从nedb获取通讯录数据
    SetFriends({ commit }, wechatId) {
        nedb.friends.find({ WeChatId: wechatId }, (err, docs) => {
            if (err) return
            commit('SET_FRIENDS', docs || [])
        })
    },
    // 批量添加好友到数据库
    AddFriends({ rootGetters, dispatch }, friends) {
        let wechatId = friends[0] ? friends[0].WeChatId : ''
        nedb.friends.insert(friends, (err, newDocs) => {
            if (err) return
            dispatch('SetFriendsMap')
            if (wechatId === rootGetters['conversation/currentWeChatId']) {
                dispatch('SetFriends', wechatId)
            }
        })
    },
    // 更新nedb的friends表
    UpdateFriends({ rootGetters, dispatch }, friend) {
        nedb.friends.update(
            { _id: friend._id },
            friend,
            { upsert: false },
            (err, numReplaced) => {
                if (err) return
                // 更新全局map
                dispatch('SetFriendsMap')
                // 如果改变的是当前的微信 自动刷新当前微信的好友列表的数据
                if (friend.WeChatId === rootGetters['conversation/currentWeChatId']) {
                    dispatch('SetFriends', friend.WeChatId)
                }
            }
        )
    },
    // 添加或更新好友的信息by FriendAddNotice
    UpdateFriendsByOne({ rootGetters, dispatch }, friend) {
        nedb.friends.update(
            {
                userId: rootGetters.userId,
                FriendId: friend.FriendId,
                WeChatId: friend.WeChatId
            },
            friend,
            { upsert: true },
            (err, numReplaced) => {
                if (err) return
                if (friend.WeChatId === rootGetters['conversation/currentWeChatId']) {
                    dispatch('SetFriends', friend.WeChatId)
                }
            })
    },
    // 删除nedb中的指定微信的friends
    RemoveAllFriensByWechatId({ dispatch }, wechatId) {
        nedb.friends.remove({ WeChatId: wechatId }, { multi: true }, (err, removedDocs) => {
            if (err) return
            dispatch('SetFriends', wechatId)
        })
    },
    // 删除nedb中的指定微信id的friend
    RemoveFriend({ rootGetters, dispatch }, message) {
        // FriendId: "wxid_9mikoz4cy2zn22"
        // WeChatId: "wxid_kg9a5uxz94nl22"
        nedb.friends.remove(
            { userId: rootGetters.userId, WeChatId: message.WeChatId, FriendId: message.FriendId },
            {},
            (err, numRemoved) => {
                if (err) return
                dispatch('SetFriends', message.WeChatId)
            }
        )
    },
    // 从nedb获取群聊数据
    SetChatRooms({ commit }, wechatId) {
        nedb.chatRooms.find({ WeChatId: wechatId }, (err, docs) => {
            if (err) return
            commit('SET_CHAT_ROOMS', docs || [])
        })
    },
    // 添加或更新群信息
    AddOrUpdateChatRoom({ rootGetters, dispatch }, room) {
        if (!room.ChatRoom) return
        nedb.chatRooms.findOne(
            {
                userId: rootGetters.userId,
                UserName: room.ChatRoom.UserName,
                WeChatId: room.WeChatId
            },
            (err, doc) => {
                if (err) return
                if (doc) {
                    let chatroom = room.ChatRoom
                    chatroom['userId'] = rootGetters.userId
                    chatroom['WeChatId'] = room.WeChatId
                    chatroom['_id'] = doc._id
                    dispatch('UpdateChatRoomById', chatroom)
                } else {
                    dispatch('AddChatRooms', room)
                }
            })
    },
    // 添加nedb的chatRooms
    AddChatRooms({ rootGetters, dispatch }, message) {
        // 如果有好友
        let userId = rootGetters.userId
        let wechatId = message.WeChatId
        let chatRooms = []
        // chatroomPushNotice
        if (message.ChatRooms) {
            for (const chatRoom of message.ChatRooms) {
                chatRoom.WeChatId = wechatId
                chatRoom.userId = userId
                chatRooms.push(chatRoom)
            }
        }
        // chatRoomAddNotice
        if (message.ChatRoom) {
            let chatRoom = message.ChatRoom
            chatRoom.WeChatId = wechatId
            chatRoom.userId = userId
            chatRooms.push(chatRoom)
        }
        if (chatRooms.length === 0) return
        // 如果有群聊
        nedb.chatRooms.insert(chatRooms, (err, newDocs) => {
            if (err) return
            if (wechatId === rootGetters['conversation/currentWeChatId']) {
                dispatch('SetChatRooms', wechatId)
                // dispatch('SetChatRoomsMap')
            }
        })
    },
    // 更新nedb的chatRooms
    UpdateChatRoom({ rootGetters, dispatch }, message) {
        nedb.chatRooms.update(
            { userId: rootGetters.userId, WeChatId: message.WeChatId, UserName: message.UserName },
            { $set: message.sqlStr },
            { multi: false },
            (err, numReplaced) => {
                if (err) return
                // 更新群聊列表
                if (message.WeChatId === rootGetters['conversation/currentWeChatId']) {
                    dispatch('SetChatRooms', message.WeChatId)
                    // dispatch('SetChatRoomsMap')
                }
            }
        )
    },
    // 更新nedb的chatRooms
    UpdateChatRoomById({ rootGetters, dispatch }, chatroom) {
        nedb.chatRooms.update(
            { _id: chatroom._id },
            chatroom,
            { multi: false },
            (err, numReplaced) => {
                if (err) return
                // 更新群聊列表
                if (chatroom.WeChatId === rootGetters['conversation/currentWeChatId']) {
                    dispatch('SetChatRooms', chatroom.WeChatId)
                    // dispatch('SetChatRoomsMap')
                }
                // 更新currentFriends
                dispatch('conversation/UpdateCurrentFriendsByRoom', chatroom, { root: true })
            }
        )
    },
    // 从数据库删除某个chatRooom
    RemoveChatRoom({ rootGetters, dispatch, commit }, message) {
        let wechatId = message.WeChatId
        nedb.chatRooms.remove(
            {
                userId: rootGetters.userId,
                WeChatId: wechatId,
                UserName: message.RoomId
            },
            { multi: false },
            (err, numRemoved) => {
                if (err) return
                if (wechatId === rootGetters['conversation/currentWeChatId']) {
                    dispatch('SetChatRooms', wechatId)
                    // dispatch('SetChatRoomsMap')
                }
                // 删除当前会话列表的会话
                dispatch('RemovConversationsByFriendId', message)
                // 如果群管理页面是该群
                // 更新当前的好友数据
                let currentFriends = rootGetters['conversation/currentFriends']
                // 当前的微信
                let currentWeChatId = rootGetters['conversation/currentWeChatId']
                // 当前的好友
                let currentFriend = currentFriends[currentWeChatId]
                if (wechatId === currentWeChatId && currentFriend && message.RoomId === currentFriend.UserName) {
                    let fmsg = {
                        wechatId: wechatId,
                        friend: {}
                    }
                    commit('conversation/SET_CURRENT_FRIENDS', fmsg, { root: true })
                }
            }
        )
    },
    // 删除nedb中的指定微信的群聊
    RemoveAllRoomByWechatId({ dispatch, commit }, wechatId) {
        nedb.chatRooms.remove(
            { WeChatId: wechatId },
            { multi: true },
            (err, removedDocs) => {
                if (err) return
                dispatch('SetChatRooms', wechatId)
                // 清空群管理页面
                let fmsg = {
                    wechatId: wechatId,
                    friend: {}
                }
                commit('conversation/SET_CURRENT_FRIENDS', fmsg, { root: true })
            })
    },
    // 设置friendsMap
    SetFriendsMap({ rootGetters, commit }) {
        let friendsMap = {}
        nedb.friends.find({ userId: rootGetters.userId }, (err, docs) => {
            for (const doc of docs) {
                if (!friendsMap[doc.WeChatId]) {
                    friendsMap[doc.WeChatId] = {}
                }
                friendsMap[doc.WeChatId][doc.FriendId] = doc
            }
        })
        commit('SET_FRIENDS_MAP', friendsMap)
    },
    // 设置chatRoomsMap
    SetChatRoomsMap({ rootGetters, commit }) {
        let chatRooms = {}
        nedb.chatRooms.find({ userId: rootGetters.userId }, (err, docs) => {
            for (const doc of docs) {
                if (!chatRooms[doc.WeChatId]) {
                    chatRooms[doc.WeChatId] = {}
                }
                chatRooms[doc.WeChatId][doc.UserName] = doc
            }
        })
        commit('SET_CHAT_ROOMS_MAP', chatRooms)
    },
    // FriendTalkNotice添加到chats数据库 ok
    AddChats({ rootGetters, dispatch }, message) {
        message.userId = rootGetters.userId
        let currentWeChatId = rootGetters['conversation/currentWeChatId']
        let currentFriendId = rootGetters['conversation/currentFriendId']
        nedb.chats.insert(message, (err, newDoc) => {
            if (err) return
            if (message.FriendId === currentFriendId) {
                // 如果收到的消息是已经在看的消息 更新消息列表
                dispatch('SetCurrentChats', currentFriendId)
                // 如果收到的消息是已经在看的消息 那么就把该消息的未读数量设为0
                dispatch('SetUnreadCnt', {
                    WeChatId: currentWeChatId,
                    FriendId: currentFriendId
                })
            }
        })
    },
    // 离线消息保存到chats
    AddChatsByHistory({ rootGetters, dispatch }, mj) {
        let messages = mj.Messages
        let chats = []
        for (const chat of messages) {
            chats.push(chat)
        }
        chats.map(item => {
            item.msgSvrId = item.MsgSvrId ? item.MsgSvrId : item.MsgId
            item.WeChatId = mj.WeChatId
            item.userId = rootGetters.userId
        })
        let currentWeChatId = rootGetters['conversation/currentWeChatId']
        let currentFriendId = rootGetters['conversation/currentFriendId']
        nedb.chats.insert(chats, (err, newDoc) => {
            if (err) return
            if (chats[0].FriendId === currentFriendId) {
                // 如果收到的消息是已经在看的消息 更新消息列表
                dispatch('SetCurrentChats', currentFriendId)
                // 如果收到的消息是已经在看的消息 那么就把该消息的未读数量设为0
                dispatch('SetUnreadCnt', {
                    WeChatId: currentWeChatId,
                    FriendId: currentFriendId
                })
            }
        })
    },
    // 根据wxid删除chats
    RemoveChatsByWxId({ rootGetters, dispatch }, message) {
        nedb.chats.remove(
            {
                userId: rootGetters.userId,
                WeChatId: message.WeChatId,
                FriendId: message.FriendId || message.UserName
            },
            { multi: true },
            (err, count) => {
                if (!err && count) {
                    dispatch('SetCurrentChats', message.WeChatId)
                }
            })
    },
    // 根据MsgId删除chats
    RemoveChatsByMsgId({ rootGetters, dispatch }, warningMsg) {
        nedb.chats.remove(
            {
                userId: rootGetters.userId,
                WeChatId: warningMsg.wechatId,
                MsgId: warningMsg.msgId.toString(),
            },
            { multi: true },
            (err, count) => {
                if (err || !count) return
                let currentWeChatId = rootGetters['conversation/currentWeChatId']
                // 如果当前的好友是警告的好友
                if (warningMsg.friendId === rootGetters['conversation/currentFriends'][currentWeChatId]) {
                    dispatch('SetCurrentChats', warningMsg.friendId)
                }
            })
    },
    // 更新数据库中的chats
    UpdateChats({ rootGetters, dispatch }, message) {
        // 更新chat的CreateTime 这个时间不是很精确
        let ct = new Date().getTime()
        // let currentWeChatId = rootGetters['conversation/currentWeChatId']
        let currentFriendId = rootGetters['conversation/currentFriendId']
        nedb.chats.update(
            { MsgId: message.MsgId },
            { $set: { msgSvrId: message.MsgSvrId, CreateTime: message.CreateTime ? message.CreateTime : ct } },
            {},
            (err, numReplaced) => {
                if (err || !numReplaced) return
                if (message.FriendId === currentFriendId) {
                    // 如果收到的消息是已经在看的消息 更新消息列表
                    dispatch('SetCurrentChats', currentFriendId)
                    // // 如果收到的消息是已经在看的消息 那么就把该消息的未读数量设为0
                    // dispatch('SetUnreadCnt', {
                    //     WeChatId: currentWeChatId,
                    //     FriendId: currentFriendId
                    // })
                }
            }
        )
    },
    // 更新聊天图片
    UpdateChatImgUrl({ rootGetters, dispatch }, message) {
        let currentWeChatId = rootGetters['conversation/currentWeChatId']
        let currentFriendId = rootGetters['conversation/currentFriendId']
        nedb.chats.findOne({ MsgId: message.MsgId }, (err, doc) => {
            if (doc) {
                let oldContent = base64.decode(doc.Content)
                let newStr = "," + '"Url":' + '"' + base64.decode(message.Content) + '"' + '}'
                let newContent = oldContent.replace(/\}$/, newStr)
                nedb.chats.update(
                    { MsgId: message.MsgId },
                    { $set: { Content: base64.encode(newContent) } },
                    {},
                    (err, numReplaced) => {
                        if (err) return
                        if (message.FriendId === currentFriendId) {
                            // 如果收到的消息是已经在看的消息 更新消息列表
                            dispatch('SetCurrentChats', currentFriendId)
                            // 如果收到的消息是已经在看的消息 那么就把该消息的未读数量设为0
                            dispatch('SetUnreadCnt', {
                                WeChatId: currentWeChatId,
                                FriendId: currentFriendId
                            })
                        }
                    }
                )
            }
        })
    },
    // 通过通知更新聊天图片
    UpdateChatImgUrlByNotice({ rootGetters, dispatch }, message) {
        let currentFriendId = rootGetters['conversation/currentFriendId']
        nedb.chats.findOne({ msgSvrId: message.MsgSvrId }, (err, doc) => {
            if (doc) {
                let oldContent = base64.decode(doc.Content)
                let newStr = "," + '"Url":' + '"' + message.Url + '"' + '}'
                let newContent = oldContent.replace(/\}$/, newStr)
                nedb.chats.update(
                    { msgSvrId: message.MsgSvrId },
                    { $set: { Content: base64.encode(newContent) } },
                    {},
                    (err, numReplaced) => {
                        let fid = doc.FriendId || doc.UserName
                        if (fid === currentFriendId) {
                            // 如果收到的消息是已经在看的消息 更新消息列表
                            dispatch('SetCurrentChats', currentFriendId)
                        }
                    }
                )
            }
        })
    },
    // 给已经撤回的消息添加标记
    SetChatRevoked({ rootGetters, dispatch }, message) {
        nedb.chats.update(
            {
                userId: rootGetters.userId,
                WeChatId: message.WeChatId,
                msgSvrId: message.TaskId
            },
            { $set: { revoked: true } },
            {},
            (err, numReplaced) => {
                if (err) return
            }
        )
    },
    // 从nedb读出我的术语
    SetMyReply({ rootGetters, commit }) {
        nedb.myReply
            .find({ userId: rootGetters.userId })
            .sort({ createTime: 1 })
            .exec((err, docs) => {
                if (!err) {
                    commit('SET_MY_REPLY', docs)
                }
            })
    },
    // 添加我的术语
    AddMyReply({ rootGetters, dispatch }, doc) {
        doc.userId = rootGetters.userId
        nedb.myReply.insert(doc, (err, newDoc) => {
            if (err) return
            dispatch('SetMyReply')
        })
    },
    // 删除我的术语
    RemoveMyReply({ dispatch }, reply_id) {
        nedb.myReply.remove({ _id: reply_id }, (err, count) => {
            if (err) return
            dispatch('SetMyReply')
        })
    },
    // 从nedb获取chats
    SetCurrentChats({ rootGetters, getters, commit }, friendId) {
        nedb.chats
            .find({
                userId: rootGetters.userId,
                WeChatId: rootGetters['conversation/currentWeChatId'],
                FriendId: friendId
            })
            .sort({ CreateTime: 1 })
            // .limit(size)
            .exec((err, docs) => {
                if (!err) {
                    commit('SET_CURRENT_CHATS', docs)
                }
            })
    },
    // 设置备注和标签操作 保存到数据库
    AddMemoTask({ rootGetters }, doc) {
        doc.userId = rootGetters.userId
        doc.result = 0 // 0表示初始状态 1表示成功 2表示失败
        nedb.memoTask.insert(doc, (err, newDoc) => {
            if (err) return
        })
    },
    // 更新memoTask
    UpdateMemoTask({ rootGetters, dispatch }, mj) {
        let flag = mj.Success ? 1 : 2
        nedb.memoTask.update(
            { TaskId: mj.TaskId },
            { $set: { result: flag } },
            {},
            (err, numReplaced) => {
            }
        )
    },
    // 从nedb获取陌生人数据
    SetMembers({ commit, rootGetters }, wechatId) {
        nedb.chatRoomMembers.findOne({ userId: rootGetters.userId, WeChatId: wechatId }, (err, doc) => {
            if (err) return
            commit('SET_MEMBERS', (doc && doc.Members) ? doc.Members : [])
        })
    },
    // 清除指定微信的陌生人数据
    RemoveMembersByWechatId({ dispatch, rootGetters }, wechatId) {
        nedb.chatRoomMembers.remove(
            { userId: rootGetters.userId, WeChatId: wechatId },
            { multi: true },
            (err, docs) => {
                if (err) return
                // 如果是会话页面当前的微信 更新members
                let currentWeChatId = rootGetters['conversation/currentWeChatId']
                if (currentWeChatId === wechatId) {
                    dispatch('SetMembers', wechatId)
                }
            })
    },
    // 陌生人数据插入nedb
    AddOrUpdateChatRoomMembers({ dispatch, rootGetters }, message) {
        let currentWeChatId = rootGetters['conversation/currentWeChatId']
        nedb.chatRoomMembers.findOne(
            { userId: rootGetters.userId, WeChatId: message.WeChatId },
            (err, doc) => {
                if (err) return
                if (doc) {
                    // 老的数据
                    let oldMembers = doc.Members
                    // 新的数据
                    let newMembers = message.Members
                    // 合并后的数据
                    let totalMembers = newMembers.concat(oldMembers);
                    // 去重
                    let temp = {};   //用于name判断重复
                    let result = [];  //最后的新数组
                    totalMembers.map(function (item, index) {
                        if (!temp[item.Wxid]) {
                            result.push(item);
                            temp[item.Wxid] = true;
                        }
                    });
                    nedb.chatRoomMembers.update(
                        { _id: doc._id },
                        { $set: { Members: result } },
                        { upsert: false },
                        (err, numReplaced) => {
                            if (err) return
                            // 如果是会话页面当前的微信 更新members
                            if (numReplaced) {
                                if (currentWeChatId === message.WeChatId) {
                                    dispatch('SetMembers', message.WeChatId)
                                }
                            }
                        })
                } else {
                    message.userId = rootGetters.userId
                    nedb.chatRoomMembers.insert(message, (err, newDoc) => {
                        if (err) return
                        // 如果是会话页面当前的微信 更新members
                        if (currentWeChatId === message.WeChatId) {
                            dispatch('SetMembers', message.WeChatId)
                        }
                    })
                }
            })
    },
    // 从nedb获取qrCode数据
    SetConversationQrCode({ commit }, wechatId) {
        nedb.qrcode.findOne({ WeChatId: wechatId, ChatRoomId: -1 }, (err, doc) => {
            if (err) return
            commit('SET_CONVERSATION_QR_CODE', doc ? doc : { WeChatId: '', ChatRoomId: -1, QrCodeUrl: '', ModifyTime: 0 })

        })
    },
    // 从nedb获取群聊的qrCode数据
    SetChatRoomQrCode({ commit }, chatRoom) {
        nedb.qrcode.findOne(
            {
                WeChatId: chatRoom.WeChatId,
                ChatRoomId: chatRoom.UserName,
            },
            (err, doc) => {
                if (err) return
                commit('SET_CHAT_ROOM_QR_CODE', doc ? doc : { WeChatId: '', ChatRoomId: -1, QrCodeUrl: '', ModifyTime: 0 })
            })
    },
    // 群管理任务保存到数据库
    AddChatRoomTask({ rootGetters }, doc) {
        doc.userId = rootGetters.userId
        doc.result = 0 // 0表示初始状态 1表示成功 2表示失败
        nedb.chatRoomTask.insert(doc, (err, newDoc) => {
            if (err) return
        })
    },
    // 更新群管理任务
    UpdateChatRoomTask({ rootGetters, dispatch }, mj) {
        let flag = mj.Success ? 1 : 2
        nedb.chatRoomTask.update(
            { TaskId: mj.TaskId },
            { $set: { result: flag } },
            {},
            (err, numReplaced) => { }
        )
    },
    // 从nedb获取好友的朋友圈数据
    SetConversationCircles({ commit }, currentFriend) {
        nedb.circles.findOne({ WeChatId: currentFriend.WeChatId, FriendId: currentFriend.FriendId }, (err, doc) => {
            if (err) return
            commit('SET_CONVERSATION_CIRCLES', doc && doc.Circles ? doc.Circles : [])
        })
    },
    // 查询大图|视频|文件的url 弃用
    QueryUrl({ rootGetters, dispatch, commit }, chat) {
        let msgSvrId = chat.msgSvrId ? chat.msgSvrId : ''
        let md5 = chat.Content.Md5 ? chat.Content.Md5 : ''
        nedb.chatDetail.findOne(
            { userId: rootGetters.userId, msgSvrId: msgSvrId, md5: md5 },
            (err, doc) => {
                if (err) return
                if (doc && doc.url) {
                    commit('conversation/SET_URL', doc.url, { root: true })
                    this.SetCurrentUrl(doc.url)
                } else {
                    // 最后从手机上获取
                    dispatch('websocket/RequestTalkDetailTask', chat, { root: true })
                }
            })
    },
    // 查询最近的一条聊天记录 然后用来获取历史消息
    QueryLastChat({ rootGetters, dispatch }, friend) {
        let friendId = friend.UserName || friend.FriendId
        nedb.chats
            .findOne({ userId: rootGetters.userId, WeChatId: friend.WeChatId, FriendId: friendId }) // 全部
            .sort({ CreateTime: -1 }) // 降序
            .exec((err, doc) => {
                if (err) return
                // let startTime = new Date().getTime() - 7 * 24 * 60 * 60 * 1000 // 获取最新一周的会话
                let startTime = 0
                let endTime = 0
                // 从手机获取离线消息
                if (doc && doc.CreateTime) {
                    // if (doc.CreateTime >= friend.UpdateTime) return
                    // startTime = Number(doc.CreateTime) + 1000
                    startTime = Number(doc.CreateTime) + 10
                }
                let thm = {
                    wechatId: friend.WeChatId,
                    friendId: friendId, // 好友id, 置空表示全部好友
                    startTime: startTime, // 开始同步的消息时间，0表示全部,UTC毫秒
                    endTime: endTime, // 结束同步的消息时间，0表示到当前时间为止
                    // flag: 0, // 获取全部时，0：只有好友， 1：只有群聊， 2：所有（好友和群聊）
                }
                dispatch('websocket/TriggerHistoryMsgPushTask', thm, { root: true })
            })
    },
    //设置红包账单
    SetLuckMoneyMap({ rootGetters, commit }) {
        nedb.luckMoney.find(
            { userId: rootGetters.userId },
            (err, docs) => {
                if (err) return
                commit('SET_LUCK_MONEY_MAP', docs)
            }
        )
    },
    // 添加红包账单
    InsertLuckMoney({ rootGetters, dispatch }, doc) {
        doc.userId = rootGetters.userId
        doc.opened = false
        nedb.luckMoney.insert(
            doc,
            (err, newDoc) => {
                if (err) return
                dispatch('SetLuckMoneyMap')
            }
        )
    },
    // 更新红包账单
    UpdateLuckMoney({ rootGetters, dispatch }, message) {
        // 红包的返回
        // Amount: 1
        // MsgKey: "wxpay://c2cbizmessagehandler/hongbao/receivehongbao?msgtype=1&channelid=1&sendid=1000039901202006027408142428640&sendusername=Uta2012&ver=6&sign=790e1223f0339c00c83dad39efc1dc217490c7aed888452e142f569678f21009c921b3c941c8e690e10cad80740f9b60cdc47d20bc8159ea28ed6bc28750735e11b399eb62e502a4d34cec2fcf3b082d"
        // Success: true
        // TaskId: "1591090754579169"
        // WeChatId: "wxid_9988ti1oz81g22"

        // 转账的返回
        // MsgKey: "1000050001202006031104408135701"
        // Success: true
        // TaskId: "15911542202927644"
        // WeChatId: "wxid_9988ti1oz81g22"

        // 数据库中已经保存的信息
        // WeChatId: message.WeChatId, //微信唯一Id
        // FriendId: message.FriendId, //聊天好友微信唯一id
        // MsgSvrId: message.MsgSvrId, //全局消息id
        // MsgKey: message.MsgKey, // 消息内容中的Key
        // TaskId: taskId.toString(), //

        nedb.luckMoney.update(
            {
                userId: rootGetters.userId,
                MsgKey: message.MsgKey,
                WeChatId: message.WeChatId
            },
            { $set: { opened: true, Amount: message.Amount } },
            {},
            (err, numReplaced) => {
                if (err) return
                dispatch('SetLuckMoneyMap')
            }
        )
    }
}

// mutations
const mutations = {
    // ===================== 功能大全用到的变量===================
    // 设置newFriends
    SET_NEW_FRIENDS(state, doc) {
        if (doc.Requests && doc.Requests.length > 0) {
            // 数据降序排列
            let requests = doc.Requests.sort((a, b) => {
                return b.ReqTime - a.ReqTime
            })
            state.newFriends = requests
        } else {
            state.newFriends = []
        }
    },
    // 设置addFriends
    SET_ADD_FRIENDS(state, docs) {
        state.addFriends = docs
    },
    // 设置僵尸粉
    SET_ZOMBIES(state, docs) {
        state.zombies = docs
    },
    // 设置工具大全的qrCodes
    SET_QR_CODE(state, doc) {
        for (const key in doc) {
            Vue.set(state.qrCode, key, doc[key])
        }
    },
    // 设置自动任务的配置文件
    SET_AUTO_TASK_CONFIG(state, config) {
        state.autoTaskConfig = config
    },
    // 设置autoReply
    SET_AUTP_REPLY(state, docs) {
        state.autoReply = docs
    },
    // 设置autoHi配置
    SET_AUTP_HI_CONFIG(state, doc) {
        for (const key in doc) {
            if (doc.hasOwnProperty(key)) {
                Vue.set(state.autoHiConfig, key, doc[key])
            }
        }
    },
    // 设置全局搜索结果
    SET_SEARCH_CONDITIONS(state, docs) {
        state.searchResults = docs
    },
    // 批量加好友的日志
    SET_AUTO_ADD_FRIEND_LOG(state, logs) {
        // docs.sort((a, b) => {
        //     return b.TaskId - a.TaskId
        // })
        state.autoAddFriendLog = logs
    },
    // 批量加好友的日志
    SET_PHONES_LIST(state, phones) {
        state.phonesList = phones
    },
    // 搜索联系人日志
    SET_FIND_CONTACT_TASK(state, docs) {
        state.findContactTaskResult = docs
    },

    // ===================== 朋友圈用到的变量 =====================
    // 朋友圈页面所选微信的朋友圈列表
    SET_CURRENT_CIRCLES(state, circles) {
        circles.sort((a, b) => {
            return b.PublishTime - a.PublishTime
        })
        // PublishTime
        state.currentCircles = circles
    },
    // 朋友圈页面所选微信的朋友圈操作日志
    SET_FRIEND_CIRCLE_LOG(state, docs) {
        docs.sort((a, b) => {
            return b.TaskId - a.TaskId
        })
        state.friendCircleLog = docs
    },
    // 朋友圈页面所选微信的通讯录
    SET_CIRCLE_FRIENDS(state, friends) {
        state.circleFriends = friends
    },
    // 朋友圈页面所选微信的标签列表
    SET_CIRCLE_LABELS(state, doc) {
        state.circleLabels = doc.Labels
    },

    // ===================== 群发助手用到的变量 ====================
    // 群发助手页面所选微信的群发日志
    SET_GROUP_SEND_LOG(state, docs) {
        // docs.sort((a, b) => {
        //     return b.TaskId - a.TaskId
        // })
        state.groupSendLog = docs
    },
    // 群发助手页面所选微信的通讯录
    SET_GROUP_SEND_FRIENDS(state, friends) {
        state.groupSendFriends = friends
    },
    // 群发助手页面所选微信的群聊
    SET_GROUP_SEND_ROOMS(state, rooms) {
        state.groupSendRooms = rooms
    },
    // 群发助手页面所选微信的标签列表
    SET_GROUP_SEND_LABELS(state, doc) {
        state.groupSendLabels = doc.Labels
    },

    // ===================== 会话页面用到的变量 ===================
    // 设置当前微信的会话
    SET_CONVERSATIONS(state, conversations) {
        let convers = []
        // 过滤掉 企业微信的群聊和企业微信好友
        convers = conversations.filter((x, index) => {
            return !x.UserName.endsWith('@im.chatroom') && !x.UserName.endsWith('@openim')
        })
        // 按时间降序
        convers.sort((a, b) => {
            return b.UpdateTime - a.UpdateTime
        })
        let newConvers = []
        // 分页 每页50
        for (let i = 0; i < convers.length; i += 50) {
            newConvers.push(convers.slice(i, i + 50))
        }
        state.conversations = newConvers
    },
    // 统计每个微信的未读消息
    SET_NEW_MESSAGE_NOTICE(state, msgMap) {
        for (const key in msgMap) {
            if (msgMap.hasOwnProperty(key)) {
                Vue.set(state.newMessageNotice, key, msgMap[key])
            }
        }
    },
    // 设置当前微信的通讯录
    SET_FRIENDS(state, friends) {
        // 按时间降序
        // friends.sort((a, b) => {
        //     return b.FriendId - a.FriendId
        // })
        let newFriends = []
        // 分页 每页50
        for (let i = 0; i < friends.length; i += 50) {
            newFriends.push(friends.slice(i, i + 50))
        }
        state.friendsAll = friends
        state.friends = newFriends
    },
    // 设置当前微信的群聊列表
    SET_CHAT_ROOMS(state, docs) {
        let newRooms = []
        // 分页 每页50
        for (let i = 0; i < docs.length; i += 50) {
            newRooms.push(docs.slice(i, i + 50))
        }
        state.chatRoomsAll = docs
        state.chatRooms = newRooms
    },
    // 设置所有的微信的好友id和好友信息的map
    SET_FRIENDS_MAP(state, friendsMap) {
        state.friendsMap = friendsMap
    },
    // 设置所有的微信的群聊id和好友信息的map
    SET_CHAT_ROOMS_MAP(state, chatRoomsMap) {
        state.chatRoomsMap = chatRoomsMap
    },
    // 设置我的术语
    SET_MY_REPLY: (state, myReplyDocs) => {
        state.myReply = myReplyDocs
    },
    // 设置当前好友的聊天记录
    SET_CURRENT_CHATS: (state, chatDocs) => {
        state.currentChats = chatDocs
    },
    // 会话页面所选微信的标签列表
    SET_LABELS(state, doc) {
        state.labels = doc.Labels
    },
    // 设置当前微信的陌生人列表
    SET_MEMBERS(state, members) {
        state.members = members
    },
    // 设置会话页面的qrCodes
    SET_CONVERSATION_QR_CODE(state, doc) {
        for (const key in doc) {
            Vue.set(state.conversationQrCode, key, doc[key])
        }
    },
    // 设置会话页面的群聊qrCodes
    SET_CHAT_ROOM_QR_CODE(state, doc) {
        for (const key in doc) {
            Vue.set(state.chatRoomQrCode, key, doc[key])
        }
    },
    // 设置会话页面所选微信的朋友圈列表
    SET_CONVERSATION_CIRCLES(state, circles) {
        circles.sort((a, b) => {
            return b.PublishTime - a.PublishTime
        })
        state.conversationCircles = circles
    },
    // 设置luckMoneyMap
    SET_LUCK_MONEY_MAP(state, docs) {
        for (const key in docs) {
            Vue.set(state.luckMoneyMap, docs[key].MsgSvrId, docs[key])
        }
    },
}

export default {
    namespaced: true,
    state,
    getters,
    actions,
    mutations
}
